<?php



/**
 * @Author:      lyt
 * @DateTime:  2017-10-19 14:38:55
 * @Description: 用于门店帮助和公道的
 */
class ScsHelpPubllcController extends BaseController
{
   /**
    * @Author:      lyt
    * @DateTime:  2017-10-19 14:39:38
    * @Description: 用于帮助信息的方法
    */
    public function helplists(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "page"=>'integer',
                "page_size"=>'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $page_size=Input::get("page_size",25);
            $page=Input::get("page",1);
            $title = Input::get("title");
            $lable = Input::get("lable");

            $hm = HelpMessage::LeftJoin('system_users as su1', 'su1.id', '=', 'help_message.updated_by')->where("help_message.status",1);
            if($lable) {
                $hm->where("help_message.lable_str",'like','%,' . $lable .',%');
            }
            if ($title) {
                $hm->where("help_message.title","like", '%' . $title . '%');
            }
            
            $count=$hm->count();
            $hm=$hm->skip($page_size*($page-1))->take($page_size)->select('help_message.id','help_message.title','help_message.updated_at','help_message.status', 'su1.name as sys_name')->orderBy("help_message.view_times","desc")->orderBy("help_message.id","asc")->get();
            foreach ($hm as $_h) {
                $bd=DB::select("SELECT
                        GROUP_CONCAT(li.`name` SEPARATOR '/') as lab_name
                    FROM
                        `help_message` hs
                    LEFT JOIN  help_message_label hml ON hs.id=hml.message_id
                    LEFT JOIN  labels_info li ON li.id = hml.label_id
                    where hs.id=?",array($_h->id)); 
                $_h->lab_name=$bd[0]->lab_name;
            }
            $lable=LabelsInfo::where("type",1)->where("status",1)->get();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>$count,"help_date"=>$hm,"lable"=>$lable));
        }while(false);
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-10-19 14:51:07
     * @Description: 用于获取帮助信息详情
     */
    public function helpdesc(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id'=>"required",
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $hm = HelpMessage::LeftJoin('system_users as su1', 'su1.id', '=', 'help_message.updated_by')->where("help_message.id",Input::get("id"))->select('help_message.id','help_message.title','help_message.updated_at','help_message.status', 'su1.name as sys_name','help_message.content')->first();
            if(is_null($hm)){
                $response = Lang::get("scs_error.help_error_31015");
                break;
            }
            $lab_arra=HelpMessageLabel::LeftJoin("labels_info","labels_info.id","=",
            "help_message_label.label_id")->where("help_message_label.message_id",Input::get("id"))->select("labels_info.id","labels_info.name")->get();
            // HelpMessage::where("id",Input::get("id"))->increment('view_times');
            DB::update("update help_message set view_times=view_times+1 where id =?",array(Input::get("id")));
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("help_info"=>$hm,"lable_info"=>$lab_arra));
        }while(false);
        // Log::info("info", array("system" => "scs" ,"event" => "getSupplyList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


   /**
    * @Author:      lyt
    * @DateTime:  2017-10-19 15:43:52
    * @Description: 用于公告列表
    */
    public function publiclists(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "page"=>'integer',
                "page_size"=>'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $page_size=Input::get("page_size",25);
            $page=Input::get("page",1);
            $title = Input::get("title");
            $lable = Input::get("lable");
            $start_time = Input::get("start_time");
            $end_time = Input::get("end_time");

            $pm = PublicMessage::LeftJoin('system_users as su1', 'su1.id', '=', 'public_message.updated_by')->where("public_message.status",1);
            if($lable) {
                $pm->where("public_message.lable_str",'like','%,'.$lable.',%');
            }
            if ($title) {
                $pm->where("public_message.title","like", '%' .$title .'%');
            }
            if ($start_time) {
                $pm->where("public_message.updated_at",">",  $start_time);
            }
            if ($end_time) {
                $pm->where("public_message.updated_at","<=", $end_time);
            }

            
            $count=$pm->count();
            $pm=$pm->skip($page_size*($page-1))->take($page_size)->select('public_message.id','public_message.title','public_message.updated_at','public_message.status', 'su1.name as sys_name')->orderBy("public_message.updated_at","desc")->get();
            foreach ($pm as $_h) {
                $bd=DB::select("SELECT
                        GROUP_CONCAT(li.`name` SEPARATOR '/') as lab_name
                    FROM
                        `public_message` pm
                    LEFT JOIN  public_message_label pml ON pm.id=pml.message_id
                    LEFT JOIN  labels_info li ON li.id = pml.label_id
                    where pm.id=?",array($_h->id)); 
                $_h->lab_name=$bd[0]->lab_name;
            }
            $lable=LabelsInfo::where("type",2)->where("status",1)->get();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>$count,"public_date"=>$pm,"lable"=>$lable));
        }while(false);
        return json_encode($response);
    }

   /**
    * @Author:      lyt
    * @DateTime:  2017-10-19 15:49:48
    * @Description: 用于获取
    */
    public function publicdesc(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id'=>"required",
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $pm = PublicMessage::LeftJoin('system_users as su1', 'su1.id', '=', 'public_message.updated_by')->where("public_message.id",Input::get("id"))->select('public_message.id','public_message.title','public_message.updated_at','public_message.status', 'su1.name as sys_name','public_message.content')->first();
            if(is_null($pm)){
                $response = Lang::get("scs_error.public_error_31016");
                break;
            }
            $lab_arra=PublicMessageLabel::LeftJoin("labels_info","labels_info.id","=",
            "public_message_label.label_id")->where("public_message_label.message_id",Input::get("id"))->select("labels_info.id","labels_info.name")->get();
            // PublicMessage::where("id",Input::get("id"))->increment('view_times');
            DB::update("update public_message set view_times=view_times+1 where id =?",array(Input::get("id")));
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("public_info"=>$pm,"lable_info"=>$lab_arra));
        }while(false);
        // Log::info("info", array("system" => "scs" ,"event" => "getSupplyList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * 门店培训信息列表
     * @param string    $token      用户token
     * @param int       $page       页码
     * @param int       $page_size  每页数据条数
     * @param string    $title      标题关键字
     * @param int       $lable      标签
     * @link http://api.anhui.com/v1/scs/helppublic/traininglists?token=ba7a6a7f92fca9205f41eb20d5b93b0f&page=1&page_size=20&title=测试&lable=
     */
    public function traininglists(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "page"=>'integer',
                "page_size"=>'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $page_size=Input::get("page_size",20);
            $page=Input::get("page",1);
            $title = Input::get("title");
            $lable = Input::get("lable");
            
            $res = TrainMessage::LeftJoin('system_users as su1', 'su1.id', '=', 'train_message.updated_by')
                    ->where('train_message.status',1);
            if($lable){
                $res->where('train_message.lable_str', 'like', '%'.$lable.'%');
            }
            if($title){
                $res->where('train_message.title', 'like', '%'.$title.'%');
            }

            $count = $res->count();
            $res = $res->skip($page_size * ($page - 1))
                    ->take($page_size)
                    ->select('train_message.id', 'train_message.title', 'train_message.updated_at', 'su1.name as sys_name')
                    ->orderBy('train_message.view_times', 'desc')
                    ->orderBy('train_message.id', 'asc')
                    ->get();
            foreach ($res as $_h) {
                $bd=DB::select("SELECT
                        GROUP_CONCAT(li.`name` SEPARATOR '/') as lab_name
                    FROM
                        `train_message` hs
                    LEFT JOIN  train_message_label hml ON hs.id=hml.message_id
                    LEFT JOIN  labels_info li ON li.id = hml.label_id
                    where hs.id=?", array($_h->id)); 
                $_h->lab_name=$bd[0]->lab_name;
            }
            //标签列表
            $lable = LabelsInfo::where('type', '3')
                    ->where('status', '1')
                    ->select('id','name')
                    ->orderBy('id','asc')
                    ->get();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array('count' => $count, 'public_data' => $res, 'lable' => $lable));
        }while(false);
        return json_encode($response);
    }
    
    /**
     * 门店培训信息详情
     * @param string    $token      用户token
     * @param int       $id         门店培训信息ID
     * @link http://api.anhui.com/v1/scs/helppublic/trainingdesc?token=42e7ac6286445c0d4106e4c8300811fb&id=2
     */
    public function trainingdesc() {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $pm = TrainMessage::LeftJoin('system_users as su1', 'su1.id', '=', 'train_message.updated_by')
                    ->where("train_message.id",Input::get("id"))
                    ->select('train_message.id','train_message.title','train_message.updated_at','train_message.status', 'su1.name as sys_name','train_message.content')
                    ->first();
            if(is_null($pm)){
                $response = Lang::get("scs_error.public_error_31016");
                break;
            }
            $lab_array = TrainMessageLabel::LeftJoin("labels_info","labels_info.id","=","train_message_label.label_id")
                    ->where("train_message_label.message_id",Input::get("id"))
                    ->select("labels_info.id","labels_info.name")
                    ->get();
            DB::update("update train_message set view_times=view_times+1 where id =?",array(Input::get("id")));
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array('training_info' => $pm, 'lable_info' => $lab_array));
        }while(false);
        return json_encode($response);
    }

   /**
    * @Author:      zy
    * @DateTime:  2018-6-05 15:43:52
    * @Description: 用于公告列表
    * @link http://api.anhui.com/v1/scs/notice/list?token=92b92b13f74dc59be3b770659bbd2a72&id=155&page_size=25&page=1&name=sa&start_time=2018-10-06&$end_time=2018-10-06&notice_type=1&is_read=1
    */
    public function noticeLists(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',

            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $page_size=Input::get("page_size",25);
            $page=Input::get("page",1);
            $skip = $page_size*($page-1);
            $name = Input::get("name"); //标题
            $start_time = Input::get("start_time"); //发布时间
            $end_time = Input::get("end_time"); //
            $notice_type = Input::get("notice_type"); //站内信类型  1:公告; 2:活动; 4:C端非五星好评; 5:门店库存预警;
            $is_read = Input::get("is_read"); //1:已读;2:未读;
            $where = " ";
            if ($name != "") $where .= " and (`name` like '%" . $name ."%' or `desc` like '%" . trim(json_encode($name), "\"") . "%' )";
            if ($start_time != "") $where .= " and `created_at`>'$start_time 00:00:00'";
            if ($end_time != "") $where .= " and `created_at`<'$end_time 23:59:59'";
            if($is_read == 2) $where .= " and `read_id` is null ";
            if($is_read == 1) $where .= " and `read_id` is not null ";
            if($notice_type == 1) $where .= " and `notice_type`=1 ";
            if($notice_type == 2) $where .= " and `notice_type` in (2,3) ";
            if ($notice_type == 4) $where .= "and `notice_type` = 4";
            if ($notice_type == 5) $where .= "and `notice_type` = 5";
            
            //use_status    排序参照    倒排
            //未读公告
            $sql_1 = "select `sc_notice`.*, `sc_notice_read`.`id` as `read_id`,8 as `use_status`"
                    . " from `sc_notice` ";
            $sql_1 .= " left join `sc_notice_shop` on `sc_notice_shop`.`notice_id` = `sc_notice`.`id` "; //筛选门店
            $sql_1 .= " left join `sc_notice_read` on `sc_notice`.`id` = `sc_notice_read`.`notice_id` and `sc_notice_read`.`user_id`={$sc_user->id} ";//已读未读
            $sql_1 .=  " where `sc_notice_read`.`id` is null and `sc_notice_shop`.`shop_id` = {$sc_user->shop_id} and `sc_notice_shop`.`status` = 1 ";//条件
            $sql_1 .= " and ((`sc_notice`.`notice_type`=1 and `sc_notice`.`status`=1)) "; //关闭的公告不显示
            
            // 未读活动
            $sql_2 = "select `sc_notice`.*, `sc_notice_read`.`id` as `read_id`,7 as `use_status`"
                    . " from `sc_notice` "
                    . " left join `sc_notice_shop` on `sc_notice_shop`.`notice_id` = `sc_notice`.`id` "
                    . " left join `sc_notice_read` on `sc_notice`.`id` = `sc_notice_read`.`notice_id` and `sc_notice_read`.`user_id`={$sc_user->id} "
                    . " where `sc_notice_read`.`id` is null and `sc_notice_shop`.`shop_id` = {$sc_user->shop_id} and `sc_notice_shop`.`status` = 1 "
                    . " and `sc_notice`.`notice_type` in (2,3) ";

            // 未读非五星评价
            $sql_3 = "select `sc_notice`.*, `sc_notice_read`.`id` as `read_id`,6 as `use_status`"
                . " from `sc_notice` "
                . " left join `sc_notice_shop` on `sc_notice_shop`.`notice_id` = `sc_notice`.`id` "
                . " left join `sc_notice_read` on `sc_notice`.`id` = `sc_notice_read`.`notice_id` and `sc_notice_read`.`user_id`={$sc_user->id} "
                . " where `sc_notice_read`.`id` is null and `sc_notice_shop`.`shop_id` = {$sc_user->shop_id} and `sc_notice_shop`.`status` = 1 "
                . " and `sc_notice`.`notice_type` = 4 ";
                
            // 未读门店预警
            $sql_7 = "select `sc_notice`.*, `sc_notice_read`.`id` as `read_id`,5 as `use_status`"
                . " from `sc_notice` "
                . " left join `sc_notice_shop` on `sc_notice_shop`.`notice_id` = `sc_notice`.`id` "
                . " left join `sc_notice_read` on `sc_notice`.`id` = `sc_notice_read`.`notice_id` and `sc_notice_read`.`user_id`={$sc_user->id} "
                . " where `sc_notice_read`.`id` is null and `sc_notice_shop`.`shop_id` = {$sc_user->shop_id} and `sc_notice_shop`.`status` = 1 "
                . " and `sc_notice`.`notice_type` = 5 ";

            //已读公告
            $sql_4 = "select `sc_notice`.*, `sc_notice_read`.`id` as `read_id`,4 as `use_status` "
                    . " from `sc_notice` "
                    . " left join `sc_notice_shop` on `sc_notice_shop`.`notice_id` = `sc_notice`.`id` "
                    . " left join `sc_notice_read` on `sc_notice`.`id` = `sc_notice_read`.`notice_id` and `sc_notice_read`.`user_id` = {$sc_user->id} "
                    . " where `sc_notice_read`.`id` is not null and `sc_notice_shop`.`shop_id` = {$sc_user->shop_id} and `sc_notice_shop`.`status` = 1 "
                . " and ((`sc_notice`.`notice_type`=1 and `sc_notice`.`status`=1)) ";
            
            //已读活动
            $sql_5 = "select `sc_notice`.*, `sc_notice_read`.`id` as `read_id`,3 as `use_status` "
                    . " from `sc_notice` "
                    . " left join `sc_notice_shop` on `sc_notice_shop`.`notice_id` = `sc_notice`.`id` "
                    . " left join `sc_notice_read` on `sc_notice`.`id` = `sc_notice_read`.`notice_id` and `sc_notice_read`.`user_id` = {$sc_user->id} "
                    . " where `sc_notice_read`.`id` is not null and `sc_notice_shop`.`shop_id` = {$sc_user->shop_id} and `sc_notice_shop`.`status` = 1 "
                    . " and `sc_notice`.`notice_type` in (2,3) ";
            //已读非五星评价
            $sql_6 = "select `sc_notice`.*, `sc_notice_read`.`id` as `read_id`,2 as use_status "
                . " from `sc_notice` "
                . " left join `sc_notice_shop` on `sc_notice_shop`.`notice_id` = `sc_notice`.`id` "
                . " left join `sc_notice_read` on `sc_notice`.`id` = `sc_notice_read`.`notice_id` and `sc_notice_read`.`user_id` = {$sc_user->id} "
                . " where `sc_notice_read`.`id` is not null and `sc_notice_shop`.`shop_id` = {$sc_user->shop_id} and `sc_notice_shop`.`status` = 1 "
                . " and `sc_notice`.`notice_type` = 4 ";
                
            //已读门店预警
            $sql_8 = "select `sc_notice`.*, `sc_notice_read`.`id` as `read_id`,1 as use_status "
                . " from `sc_notice` "
                . " left join `sc_notice_shop` on `sc_notice_shop`.`notice_id` = `sc_notice`.`id` "
                . " left join `sc_notice_read` on `sc_notice`.`id` = `sc_notice_read`.`notice_id` and `sc_notice_read`.`user_id` = {$sc_user->id} "
                . " where `sc_notice_read`.`id` is not null and `sc_notice_shop`.`shop_id` = {$sc_user->shop_id} and `sc_notice_shop`.`status` = 1 "
                . " and `sc_notice`.`notice_type` = 5 ";

            $sql = "select * from ( ($sql_1) UNION ALL ($sql_2) UNION ALL ($sql_3) UNION ALL ($sql_4) UNION ALL ($sql_5) UNION ALL ($sql_6) UNION ALL ($sql_7) UNION ALL ($sql_8)) as a where 1=1 $where  order by `use_status` desc,`created_at` desc  limit $skip,$page_size";

            $count_sql = "select count(*) as count from ( ($sql_1) UNION ALL ($sql_2) UNION ALL ($sql_3) UNION ALL ($sql_4) UNION ALL ($sql_5) UNION ALL ($sql_6) UNION ALL ($sql_7) UNION ALL ($sql_8)) as a where 1=1 $where";

            $count = DB::select($count_sql);
            $count = $count[0]->count;
            $notice = DB::select($sql);
            
            //为每一条消息补充创建人
            if ($count > 0 ) {
                foreach ($notice as $_notice) {
                    if ($_notice->created_type == 1) {
                        $_notice->created_user = SystemUser::select("name")->find($_notice->created_by);
                    }
                    if ($_notice->created_type == 2) {
                        $_notice->created_user = MktUser::select("user_name","real_name")->find($_notice->created_by);
                    }
                    if ($_notice->created_type == 3) {
                        $_notice->created_user = Users::select('real_name')->find($_notice->created_by);
                        $_notice->desc = json_decode($_notice->desc);
                        $_notice->name = $_notice->desc->content;
                    }
                    if ($_notice->created_type == 4) {
                        $_notice->created_user = '系统';
                    }
                }
            }

            //全部数量未读数量
            $all_not_read_sql = "select * from  `sc_notice`"
                    . " left join `sc_notice_shop` on `sc_notice_shop`.`notice_id` = `sc_notice`.`id` "
                    . " left join `sc_notice_read` on `sc_notice`.`id` = `sc_notice_read`.`notice_id` and `sc_notice_read`.`user_id`={$sc_user->id} "
                    . " where `sc_notice_read`.`id` is null and `sc_notice_shop`.`shop_id` = {$sc_user->shop_id} "
                    . "and `sc_notice_shop`.`status` = 1 "
                            . "and ((`sc_notice`.`notice_type`=1 and `sc_notice`.`status`=1) or (`sc_notice`.`notice_type` in (2,3)) or (`sc_notice`.`notice_type` = 4 and `sc_notice`.`status`=1) or (`sc_notice`.`notice_type` = 5 and `sc_notice`.`status`=1)) ";

            $all_not_read_count = DB::select($all_not_read_sql);
            $all_not_read = count($all_not_read_count);

            //修改未读消息条数计算方式
            $statusAll = [
                'activityNotRead' => 0,
                'noticeNotRead' => 0,
                'commentNotRead' => 0,
                'warnNotRead' => 0,
                'allNotRead' => $all_not_read,
            ];

            if ($all_not_read > 0) {
                foreach ($all_not_read_count as $statusValue) {
                    if ($statusValue->notice_type == 5) {               //门店库存预警
                        $statusAll['warnNotRead'] += 1;
                        continue;
                    }
                    if ($statusValue->notice_type == 4) {               //C端非五星评价
                        $statusValue->desc = json_decode($statusValue->desc);
                        $statusAll['commentNotRead'] += 1;
                        continue;
                    }
                    if ($statusValue->notice_type == 1) {               //公告信息
                        $statusAll['noticeNotRead'] += 1;
                        continue;
                    }
                    if (in_array($statusValue->notice_type, [2, 3])) {  //活动
                        $statusAll['activityNotRead'] += 1;
                        continue;
                    }
                }
            }

            //return $statusAll;

            //公告数量，排除关闭的   已弃用
            /*$notice_not_read = ScNotice::select("sc_notice.*","sc_notice_read.id as read_id")
                    ->leftJoin("sc_notice_shop","sc_notice_shop.notice_id","=","sc_notice.id")
                    ->leftJoin("sc_notice_read",function($query)use ($sc_user){
                        $query->On("sc_notice.id", "=", "sc_notice_read.notice_id")
                        ->where('sc_notice_read.user_id', '=', $sc_user->id);
            })->whereNull("sc_notice_read.id")
                    ->where("notice_type",1)
                    ->where("sc_notice.status",1)
                    ->where("sc_notice_shop.shop_id",$sc_user->shop_id)
                    ->where("sc_notice_shop.status",1)
                    ->count();

            //活动数量
            $activity_not_read = ScNotice::select("sc_notice.*","sc_notice_read.id as read_id")
                    ->leftJoin("sc_notice_shop","sc_notice_shop.notice_id","=","sc_notice.id")
                    ->leftJoin("sc_notice_read",function($query)use ($sc_user){
                        $query->On("sc_notice.id", "=", "sc_notice_read.notice_id")
                        ->where('sc_notice_read.user_id', '=', $sc_user->id);
            })->whereNull("sc_notice_read.id")
                    ->whereIn("notice_type",[2,3])
                    ->where("sc_notice_shop.shop_id",$sc_user->shop_id)
                    ->where("sc_notice_shop.status",1)
                    ->count();*/
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>$count,"list"=>$notice,"status" =>ScNotice::$status,"notice_type"=>ScNotice::$notice_type,"all_not_read"=>$statusAll['allNotRead'],"notice_not_read"=>$statusAll['noticeNotRead'],"activity_not_read"=>$statusAll['activityNotRead'], "comment_not_read" => $statusAll['commentNotRead'], "warn_not_read" => $statusAll['warnNotRead']));
        }while(false);
        //Log::info("info", array("system" => "scs" ,"event" => "notice/list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
   /**
    * @Author:      zy
    * @DateTime:  2018-6-05 15:43:52
    * @Description: 用于面板活动
    */
    public function noticeActivity(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            
            $notice_type = Input::get("notice_type"); //站内信类型  2：活动包 3 优惠活动,
            $name = Input::get("name"); //活动名称模糊检索
            $start_time = date("Y-m-d H:i:s", strtotime("-1 year"));  //一年以内的所有活动
            $end_time = date("Y-m-d H:i:s"); 
            $date= date("Y-m-d H:i:s");
            $where = "";
            if($notice_type != ""){
                $where .= " and notice_type=$notice_type ";
            }else{
                $where .= " and notice_type in (2,3) ";
            }
            if ($name != "")$where .= " and sc_notice.name like '%$name%' ";

            //有效的活动，活动包  开启的，时间已经开始的，时间未结束的
            $sql_1 = "select `sc_notice`.*,3 as use_status from `sc_notice` "
                    . " left join `sc_notice_shop` on `sc_notice_shop`.`notice_id` = `sc_notice`.`id` "
                    . " where `sc_notice`.`begin_time` < '$date' and `sc_notice`.`end_time` > '$date' and `sc_notice`.`status` = 1 "
                    . $where
                    . " and `sc_notice`.`created_at` > '$start_time' and `sc_notice`.`created_at` <= '$end_time' and `sc_notice_shop`.`shop_id` = {$sc_user->shop_id} and `sc_notice_shop`.`status` = 1 "
                    . " order by `sc_notice`.`product_type` asc, `sc_notice`.`begin_time` desc";

            //有效的活动，活动包  开启的，时间未开始的
            $sql_2 = "select `sc_notice`.*,2 as use_status from `sc_notice` "
                    . "left join `sc_notice_shop` on `sc_notice_shop`.`notice_id` = `sc_notice`.`id` "
                    . "where `sc_notice`.`begin_time` > '$date' and `sc_notice`.`status` = 1 "
                    . $where
                    . "and `sc_notice`.`created_at` > '$start_time' and `sc_notice`.`created_at` < '$end_time' and `sc_notice_shop`.`shop_id` = {$sc_user->shop_id} and `sc_notice_shop`.`status` = 1 "
                    . "order by `sc_notice`.`product_type` asc, `sc_notice`.`begin_time` desc";
        
            //无效的活动，活动包 关闭的 或 时间已结束的
            $sql_3 = "select `sc_notice`.*,1 as use_status from `sc_notice` "
                    . "left join `sc_notice_shop` on `sc_notice_shop`.`notice_id` = `sc_notice`.`id` "
                    . " where (`sc_notice`.`end_time` < '$date' or `sc_notice`.`status` = 0 ) "
                    . $where
                    . "and `sc_notice`.`created_at` > '$start_time' and `sc_notice`.`created_at` < '$end_time' and `sc_notice_shop`.`shop_id` = {$sc_user->shop_id} and `sc_notice_shop`.`status` = 1 "
                    . "order by `sc_notice`.`product_type` asc, `sc_notice`.`begin_time` desc";
                    
                    
            $sql = "select * from ( ($sql_1) UNION ALL ($sql_2) UNION ALL ($sql_3)) as a order by use_status desc,notice_type asc,begin_time desc";
            
            $count_sql = "select count(*) as count from ( ($sql_1) UNION ALL ($sql_2) UNION ALL ($sql_3) ) as a";

            $count = DB::select($count_sql);
            $count = $count[0]->count;
            $notice = DB::select($sql);
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>$count,"list"=>$notice,"status" =>ScNotice::$status,"notice_type"=>ScNotice::$notice_type));
        }while(false);
        //Log::info("info", array("system" => "scs" ,"event" => "notice/activity", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
   /**
    * @Author:      zy
    * @DateTime:  2018-6-05 15:43:52
    * @Description: 头部滚动条 
    */
    public function notReadNotice(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            //公告最新的一条
            $notice = ScNotice::select("sc_notice.*")
                    ->leftJoin("sc_notice_shop","sc_notice_shop.notice_id","=","sc_notice.id")
                    ->orderBy("sc_notice.created_at","DESC") //产品说的这个地方按更新时间
                    ->where("sc_notice_shop.shop_id",$sc_user->shop_id)
                    ->where("sc_notice_shop.status",1)
                    ->where("sc_notice.status",1)
                    ->where("sc_notice.notice_type",1);
            $notice = $notice->first();
            //标签
            if($notice){
                $la = trim($notice->lable_str,",");
                if (!empty($la)) {
                    $la = explode(",", $la);
                    $notice->labels_Info = LabelsInfo::whereIn('id',$la)->get();
                } 
            }

            $date = date("Y-m-d H:i:s");
            //活动包
            $activity = ScNotice::select("sc_notice.*")
                    ->leftJoin("sc_notice_shop","sc_notice_shop.notice_id","=","sc_notice.id")
                    ->orderBy("sc_notice.created_at","DESC")
                    ->where("sc_notice_shop.shop_id",$sc_user->shop_id)
                    ->where("sc_notice.end_time",">",$date)
                    ->where("sc_notice_shop.status",1)
                    ->where("sc_notice.status",1)
                    ->where("sc_notice.notice_type",2);
            $a_count=$activity->count();
            $activity = $activity->get();
            $list = [];
            $count = 0;
            if (!is_null($notice))  $list[] = $notice->toArray();
            if ($a_count > 0) {
                if (isset($list)){
                    $activity_arr = $activity->toArray();
                    $list = array_merge($list, $activity_arr);
                    $count = $a_count + 1;
                }else{
                    $list = $notice->toArray();
                    $count = $a_count;
                }
            }

            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>$count,"list"=>$list,"status" =>ScNotice::$status,"notice_type"=>ScNotice::$notice_type));
        }while(false);
        //Log::info("info", array("system" => "scs" ,"event" => "notice/notReadNotice", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
   /**
    * @Author:      zy
    * @DateTime:  2018-6-06 9:43:52
    * @Description: 站内信详情 
    * @link http://api.anhui.com/v1/scs/notice/noticeInfo?token=92b92b13f74dc59be3b770659bbd2a72&id=180
    */
    public function noticeInfo(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required', //站内信详情
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $id = Input::get("id"); //站内信id
            $info = ScNotice::find($id);
            if (is_null($info)) {
                $response = Lang::get("scs_error.notice_not_exit_110001");
                break;
            }
            
            $status = ScNoticeShop::where('shop_id',$sc_user->shop_id)
                    ->where('notice_id',$id)
                    ->where('status',1)
                    ->first();
            if (is_null($status)) {
                $response = Lang::get("scs_error.notice_no_auth_110002");
                break;
            }
            
            //发布人信息
            if ($info->created_type == 1) {
                $info->created_user = SystemUser::select("name")->find($info->created_by);
                
                $pm = PublicMessage::find($info->activity_base_id);
                $pm->view_times += 1;
                $pm->save();
            }
            if ($info->created_type == 2) {
                $info->created_user = MktUser::select("user_name","real_name")->find($info->created_by);
            }

            if ($info->created_type == 3) {
                $info->created_user = Users::select('real_name')->find($info->created_by);
                $info->desc = json_decode($info->desc);
                $info->lable_str = $info->desc->lable_str;
            }
            //门店库存预警
            if ($info->created_type == 4) {
                $info->created_user = '系统';
            }
            
            //标签
            if ($info->notice_type == 1) {
                $la = trim($info->lable_str,",");
                if (!empty($la)) {
                    $la = explode(",", $la);
                    $info->labels_Info = LabelsInfo::whereIn('id',$la)->get();
                }
            }
            
            //活动包 包含服务  和耗材
            if ($info->notice_type == 2 ) {
                $pap=ProductActivityPackage::leftJoin("product_package","product_activity_package.package_id","=","product_package.id")
                        ->where('product_activity_id',$info->activity_base_id)
                        ->select('package_id','product_activity_package.id','product_package.name')->get();

                if (!empty($pap)){
                    foreach ($pap as $value){
                        $product_pack_item = ProductPackItem::leftjoin("supply_classification","supply_classification.id","=","product_pack_item.item_id" )
                                ->where("pack_id",$value->package_id)
                                ->where("type",3)
                                ->where("product_pack_item.status",1)
                                ->select("supply_classification.name","product_pack_item.item_id")
                                ->get();

                        foreach ($product_pack_item as $v) {
                            $papi = ProductActivityPackageItem::where("subject",$v->item_id)
                                    ->where("product_activity_package_item.product_activity_package_id",$value->id)
                                    ->select("id","supply_item_id","number")
                                    ->first();

                            $v->papi = $papi;
                            if (!empty($papi->supply_item_id)) {
                                $v->item = SupplyItem::getCacheItemInfo($papi->supply_item_id);
                            }
                        }
                        $value->product_pack_item = $product_pack_item;
                    }
                    //$value->id => product_activity_package_id    
                }
                $info->pap = $pap;
                $info->shops = ScNoticeShop::select("sc_notice_shop.id","sc_notice_shop.shop_id","maintenance_shops.name")
                            ->leftJoin("maintenance_shops","maintenance_shops.id","=","sc_notice_shop.shop_id")
                            ->where("notice_id",$info->id)
                            ->where("sc_notice_shop.status",1)
                            ->groupBy("shop_id")
                            ->get();
            }
            
            //优惠活动 优惠卷信息
            if ($info->notice_type == 3) {
                $activity_coupon_info = ActivityCouponInfo::where('activity_id',$info->activity_base_id)->where('status',1)->get();
                if($activity_coupon_info){
                    foreach($activity_coupon_info as $_a_c_i){
                        $_a_c_i->coupon_base_info = CouponBaseInfo::where('id',$_a_c_i->coupon_base_info_id)->first();
                    }
                }
                $info->activity_coupon_info = $activity_coupon_info;
                $info->shops = ScNoticeShop::select("sc_notice_shop.id","sc_notice_shop.shop_id","maintenance_shops.name")
                            ->leftJoin("maintenance_shops","maintenance_shops.id","=","sc_notice_shop.shop_id")
                            ->where("notice_id",$info->id)
                            ->where("sc_notice_shop.status",1)
                            ->groupBy("shop_id")
                            ->get();
            }
            
            //门店库存预警      获取预警详情
            if ($info->notice_type == 5) {
                $select_item_arr = [
                    'shop_id', 'item_id', 'item_name', 'supply_classification_id', 'supply_classification_name', 
                    'level_1_id', 'level_1_name', 'level_2_id', 'level_2_name', 'level_3_id', 'level_3_name', 
                    'item_code', 'brand_id', 'brand_name', 'series_id', 'series_name', 'model', 'sale_unit_id', 
                    'sale_unit_name', 'car_model_comments', 'location', 'storage_number', 'storage_amount', 
                    'max_number', 'min_number', 'notice_id', 'start_date', 'end_date', 'created_at', 'created_by', 
                ];
                $item_list = MaintenanceWarehouseWarnAnalyze::where('shop_id', $sc_user->shop_id)
                        ->where('notice_id', $id)
                        ->select($select_item_arr)
                        ->orderBy('level_1_id')
                        ->orderBy('level_2_id')
                        ->orderBy('level_3_id')
                        ->orderBy('brand_id')
                        ->orderBy('item_code')
                        ->get()
                        ->toArray();
                $info->item_list = $item_list;
            }

            $insert = ScNoticeRead::where("user_id",$sc_user->id)
                    ->where("shop_id","=",$sc_user->shop_id)
                    ->where("notice_id",$id)
                    ->first();

            if (is_null($insert)) {
                $insert = new ScNoticeRead();
                $insert->notice_id = $id;
                $insert->shop_id = $sc_user->shop_id;
                $insert->user_id = $sc_user->id;
            }
            $insert->updated_at = date("Y-m-d H:i:s");
            $insert->save();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("info"=>$info,"status" =>ScNotice::$status,"notice_type"=>ScNotice::$notice_type));
        }while(false);
            //Log::info("info", array("system" => "scs" ,"event" => "notice/noticeInfo", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      sqq
     * @DateTime:  2018-06-11 15:38:52
     * @Description: 站内信一键已读
     */
    public function alreadyRead(){
            $validator = Validator::make(Input::all(),
                array(
                    'token' => 'required',
                    'id' => 'required', //站内信ID
                )
            );
            $response = array('code' => 0, 'msg' => 'ok');
            do{
                if($validator->fails()) {
                    $response = Lang::get("scs_error.station_args_error_31001");
                    $response["result"]=$validator->messages()->all();
                    break;
                }
                $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
                if(is_null($sc_user)){
                    break;
                }
                $id = json_decode(Input::get("id"), true); //站内信id
                //查询当前用户当前站内信是否已读，已读不操作，未读变状态为已读
                $sql = ScNoticeRead::whereIn("notice_id",$id)
                    ->where("user_id",$sc_user->id)
                    ->get()
                    ->toArray();
                $sql = array_column($sql, 'notice_id');
                $ids = array_diff($id, $sql);
                if($ids){
                    foreach($ids as $val){
                        $multipleData[] = [
                            'notice_id'=>$val,
                            'shop_id'=>$sc_user->shop_id,
                            'user_id'=>$sc_user->id,
                            'created_at'=>date("Y-m-d H:i:s", time()),
                            'updated_at'=>date("Y-m-d H:i:s", time()),
                        ];
                    }
                    if($multipleData){
                        $arr = ScNoticeRead::insert($multipleData);
                    }
                }
                $response = array('code' => 0, 'msg' => 'ok', 'result' => array("info"=>$id));
            }while(false);
            //Log::info("info", array("system" => "scs" ,"event" => "notice/NOticeInfo", 'input' =>Input::all() ,"output" => $response));
            return json_encode($response);
        }

    
}